package com.csust.cg.mongodb.service.impl;

import com.csust.cg.mongodb.domain.Result;
import com.csust.cg.mongodb.domain.vo.CollectionVO;
import com.csust.cg.mongodb.service.CollectionsService;
import com.csust.cg.mongodb.utils.MongoUtils;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoDatabase;
import org.bson.BsonDocument;
import org.bson.BsonString;
import org.bson.Document;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

/**
 * @author chenguang
 */
@Service
public class CollectionsServiceImpl implements CollectionsService {
    @Override
    public Result getCollectionsInfoList(String connectionId, String databaseName) {
        MongoClient client = MongoUtils.getClient(connectionId);
        MongoDatabase database = client.getDatabase(databaseName);
        List<CollectionVO> list = new LinkedList<>();
        for (String collection : database.listCollectionNames()) {
            if ("system.version".equals(collection) || "system.sessions".equals(collection)) {
                continue;
            }
            Document document = database.runCommand(new BsonDocument("collStats", new BsonString(collection)));
            CollectionVO vo = new CollectionVO();
            vo.setNs(document.getString("ns"));
            vo.setSize(document.getInteger("size"));
            vo.setCount(document.getInteger("count"));
            vo.setAvgObjSize(document.getInteger("avgObjSize"));
            vo.setStorageSize(document.getInteger("storageSize"));
            vo.setNIndexes(document.getInteger("nindexes"));
            vo.setTotalIndexSize(document.getInteger("totalIndexSize"));
            vo.setTotalSize(document.getInteger("totalSize"));
            list.add(vo);
        }
        MongoUtils.closeClient(client);
        return Result.success(list);
    }

    @Override
    public Result createCollection(String connectionId, String databaseName, String collectionName) {
        MongoClient client = MongoUtils.getClient(connectionId);
        client.getDatabase(databaseName).createCollection(collectionName);
        MongoUtils.closeClient(client);
        return Result.success();
    }

    @Override
    public Result dropCollection(String connectionId, String databaseName, String collectionName) {
        MongoClient client = MongoUtils.getClient(connectionId);
        client.getDatabase(databaseName).getCollection(collectionName).drop();
        MongoUtils.closeClient(client);
        return Result.success();
    }
}
